importClass("androidx.core.content.FileProvider");

const INTERVAL = 30000; //任务拉取间隔30秒
const HEARTBEAT_INTERVAL = 20000; //心跳间隔20秒
const MISSION_URL = "http://db.leyouapp.cn:8880/task-log/get"; //拉取任务地址
const MISSION_URL_TEST = 'https://mockapi.eolinker.com/ySAhKdv106542872c07011c6f65e0eb6eb6b6748527e6cc/user/points.php'; //测试任务地址
const REPORT_URL = "http://db.leyouapp.cn:8880/task-log-phone/add"; //上报任务地址6
const FAIL_URL = "http://db.leyouapp.cn:8880/task-log-phone/error"; //失败通知地址
const HEARTBEAT_URL = "http://db.leyouapp.cn:8880/hp"; //心跳地址
const ACTIVEE_URL = "http://db.leyouapp.cn:8880/member-phone/add"; //上报设备地址
const CLICK_REPORT_URL = "http://db.leyouapp.cn:8880/click"; //点击广告上报地址
const APP_VERSION = '1.0.8'; //脚本版本

const Game_Activity = "org.cocos2dx.javascript.AppActivity";
const MainActivity = "com.lxl.test.MainActivity";
const TT_Reward_Activity = "com.bytedance.sdk.openadsdk.activity.TTRewardExpressVideoActivity";
const Mercury_PortraitRewardActivity = "com.mercury.sdk.activity.PortraitRewardActivity";
const GDT_Reward_Activity = "com.qq.e.ads.RewardvideoPortraitADActivity";
const TT_Splash_Activity = "com.bytedance.sdk.openadsdk.activity.base.TTDelegateActivity";
const Byte_Dance_Activity = "com.bytedance.sdk.openadsdk.core.m";
const android_Launcher = "com.android.launcher3.Launcher";
const DialtactsActivity = "com.android.dialeer.DialtactsActivity";
const FrameLayout = "android.widget.FrameLayout";
const LinearLayout = "android.widget.LinearLayout";
const Dialog = "android.app.Dialog";
const QQAD = "com.qq.e.ads.PortraitADActivity";
const RewardvideoPortraitADActivity = "com.qq.e.ads.RewardvideoPortraitADActivity"; //斯蒙广告视频场景
const SigmobAdActivity = "com.sigmob.sdk.base.common.AdActivity"; //海星广告视频场景

const splash_close_id = "tt_splash_skip_btn";
const insert_close_id = "tt_insert_dislike_icon_img";
const reward_close_id = "iv_arp_close";
const GDT_reward_closd = "android.widget.ImageView";
const Le_clear_button = "floating_action_button";

const Sleep_time = 2000;
const FAIL_LIMIT = 3; //失败尝试限制
const ENV = "prod";

let video_pro = 50; //穿山甲视频点击率
let cha_pro = 50; //穿山甲插屏点击率
let tencent_video_pro = 50; //优量汇视频点击率
let tencent_cha_pro = 50;  //优量汇插屏点击率
let AppName = "";
let lastApp = null;
let startTime = 5;
let endTime = 10;
let taskTotal = 0;
let doneTaskRatio = 0;
let doneTaskTotal = 0;
let vStart = 0;
let vEnd = 0;
let currentCity = null;
let vpnIp = null;

//检测无障碍模式是否启用
auto.waitFor();

//保持屏幕常量
device.keepScreenOn();

run();

/**
* 定时任务
* @author guxiang
*/
function run() {
    outputMessage('开始运行');
    let deviceId = device.getIMEI();
    if (deviceId == null) {
        deviceId = device.getAndroidId();
    }
    if (device.device == 'HWSLA-Q') {
        console.show();
        sleep(1500);
        console.setPosition(0, 750);
        sleep(1500);
        console.setSize(300, 250);
    } else if (device.device == 'le_x620') {
        console.show();
        sleep(1500);
        console.setPosition(0, 1200);
        sleep(1500);
        console.setSize(395 , 320);
    } else {
        console.show();
        sleep(1500);
        console.setPosition(0, 1200);
        sleep(1500);
        console.setSize(450 , 370);
    }

    while (true) {
        try {
            threads.start(closeInstall);
            //检测WIFI开关
            //checkWifiStatus();
            sleep(5500);

            //清空日志板
            console.clear();
            //从服务器拉取任务信息
            let mission = getTask();
            outputMessage('拉取任务');
            if (mission.data && mission.data.taskAppName) {
                let taskName = mission.data.taskAppName;
                taskTotal = mission.data.taskTotal;
                doneTaskRatio = mission.data.doneTaskRatio;
                doneTaskTotal = mission.data.doneTaskTotal;
                //输出任务开始时间
                let time = new Date();
                console.info(dateFtt("yyyy年MM月dd日 hh时mm分ss秒", time));
                start(taskName, mission.data.opt.videoNum, mission.data.opt.insertScreenNum, mission.data.opt.videoClickRate, mission.data.opt.insertScreenRate, mission.data.opt.fixedRate, mission.data.opt.openScreenRate, mission.data.opt.startTime, mission.data.opt.endTime, mission.data.opt.eVideoClickRate, mission.data.opt.eInsertScreenRate, mission.data.taskLogId, 1, mission.data.opt.videoStartTime, mission.data.opt.videoEndTime, mission.data.opt.appDownloadLink, mission.data.opt.appDownloadName, mission.data.type, mission.data.appName, mission.data.packageName);
            }
            lastApp = AppName;
            cutdownDongtaiIp();
            outputMessage('任务结束');
            //心跳
            heartbeat();
            sleep(10000);
            //释放子进程资源
            clearTheards();
        } catch (e) {
            lastApp = AppName;
            //异常
            //彻底关闭分身
            killApp(AppName);
            cutdownDongtaiIp();
            clearTheards();
            outputMessage(e);
            sleep(4000);
        }
    }
}

/**
 * 检测WIFI状态
 */
function checkWifiStatus() {
    if (ENV != 'local') {
        let wifiManager = context.getSystemService(context.WIFI_SERVICE);
        if (wifiManager != null) {
            let wifiState = wifiManager.getWifiState();
            if (wifiState == 3) {
                throw new Error('请关闭WIFI运行');
            }
        }
    }
}

/**
* 获取任务信息
* @author guxiang
*/
function getTask() {
    let url = MISSION_URL + deviceInfo();
    if (ENV == 'local') {
        url = MISSION_URL_TEST + deviceInfo();
    }
    let res = http.get(url);
    if (res.statusCode == 200) {
        let resp = JSON.parse(res.body.string());
        outputMessage('code: ' + resp.code);
        if (resp.code == '10000') {
            return resp;
        } else if (resp.code == '300') {
            outputMessage('IP冲突');
            throw new Error('重新拉取');
        } else {
            outputMessage(resp.msg);
            throw new Error(resp.msg);
        }
    } else {
        throw new Error(resp.msg);
    }
}

function clearTheards() {
    threads.shutDownAll();
}

/**
 * 获取本地存储实例
 */
function getDbInstance() {
    let storage = storages.create("local_db");
    return storage;
}

/**
 * 加载APP
 * @param {*} appName 应用名称
 * @author guxiang
 */
function loadingApp(appName, idx, openScreenRate) {
    let ran = Math.random() * 100;
    let openRate = openScreenRate * 100;

    let loading = app.launchApp(appName);
    if (!loading) return false;

    checkAuthGranty();
    // if (appName.indexOf('摩天轮') != -1 || appName.indexOf('黑点') != -1 || appName.indexOf('海盗') != -1) {
    //     if (loopForActivity(20, 'SplashActivity', 500)) {
    //         if (ran < openRate) {
    //             sleep(3500);
    //             outputMessage("点击开屏广告");
    //             let offsetX = getRandom(50, 200);
    //             let offsetY = getRandom(50, 200);
    //             let randSeed = getRandom(1, 100);
    //             if (randSeed < 50) {
    //                 let clickX = device.width - offsetX;
    //                 let clickY = offsetY;
    //                 let randNum = getRandom(1, 10);
    //                 if (randNum > 7) {
    //                     coordinateClick(clickX, clickY, 2500);
    //                 } else if (randNum >= 7 && randNum < 9) {
    //                     coordinateClick(clickX, clickY, 1000);
    //                     offsetX = getRandom(50, 200);
    //                     offsetY = getRandom(50, 200);
    //                     clickX = device.width - offsetX;
    //                     clickY = offsetY;
    //                     coordinateClick(clickX, clickY, 1000);
    //                 } else {
    //                     coordinateClick(clickX, clickY, 500);
    //                     offsetX = getRandom(50, 200);
    //                     offsetY = getRandom(50, 200);
    //                     clickX = device.width - offsetX;
    //                     clickY = offsetY;
    //                     coordinateClick(clickX, clickY, 500);
    //                     offsetX = getRandom(50, 200);
    //                     offsetY = getRandom(50, 200);
    //                     clickX = device.width - offsetX;
    //                     clickY = offsetY;
    //                     coordinateClick(clickX, clickY, 500);
    //                 }
    //             } else if (randSeed >= 50 && randSeed < 70) {
    //                 let clickX = offsetX;
    //                 let clickY = offsetY;
    //                 let randNum = getRandom(1, 10);
    //                 if (randNum > 7) {
    //                     coordinateClick(clickX, clickY, 2500);
    //                 } else if (randNum >= 7 && randNum < 9) {
    //                     coordinateClick(clickX, clickY, 1000);
    //                     offsetX = getRandom(50, 200);
    //                     offsetY = getRandom(50, 200);
    //                     clickX = device.width - offsetX;
    //                     clickY = offsetY;
    //                     coordinateClick(clickX, clickY, 1000);
    //                 } else {
    //                     coordinateClick(clickX, clickY, 500);
    //                     offsetX = getRandom(50, 200);
    //                     offsetY = getRandom(50, 200);
    //                     clickX = device.width - offsetX;
    //                     clickY = offsetY;
    //                     coordinateClick(clickX, clickY, 500);
    //                     offsetX = getRandom(50, 200);
    //                     offsetY = getRandom(50, 200);
    //                     clickX = device.width - offsetX;
    //                     clickY = offsetY;
    //                     coordinateClick(clickX, clickY, 500);
    //                 }
    //             } else if (randSeed >= 70 && randSeed < 80) {
    //                 let clickX = offsetX;
    //                 let clickY = device.height - offsetY;
    //                 let randNum = getRandom(1, 10);
    //                 if (randNum > 7) {
    //                     coordinateClick(clickX, clickY, 2500);
    //                 } else if (randNum >= 7 && randNum < 9) {
    //                     coordinateClick(clickX, clickY, 1000);
    //                     offsetX = getRandom(50, 200);
    //                     offsetY = getRandom(50, 200);
    //                     clickX = device.width - offsetX;
    //                     clickY = offsetY;
    //                     coordinateClick(clickX, clickY, 1000);
    //                 } else {
    //                     coordinateClick(clickX, clickY, 500);
    //                     offsetX = getRandom(50, 200);
    //                     offsetY = getRandom(50, 200);
    //                     clickX = device.width - offsetX;
    //                     clickY = offsetY;
    //                     coordinateClick(clickX, clickY, 500);
    //                     offsetX = getRandom(50, 200);
    //                     offsetY = getRandom(50, 200);
    //                     clickX = device.width - offsetX;
    //                     clickY = offsetY;
    //                     coordinateClick(clickX, clickY, 500);
    //                 }
    //             } else if (randSeed >= 80 && randSeed < 90) {
    //                 let clickX = device.width - offsetX;
    //                 let clickY = device.height - offsetY;
    //                 let randNum = getRandom(1, 10);
    //                 if (randNum > 7) {
    //                     coordinateClick(clickX, clickY, 2500);
    //                 } else if (randNum >= 7 && randNum < 9) {
    //                     coordinateClick(clickX, clickY, 1000);
    //                     offsetX = getRandom(50, 200);
    //                     offsetY = getRandom(50, 200);
    //                     clickX = device.width - offsetX;
    //                     clickY = offsetY;
    //                     coordinateClick(clickX, clickY, 1000);
    //                 } else {
    //                     coordinateClick(clickX, clickY, 500);
    //                     offsetX = getRandom(50, 200);
    //                     offsetY = getRandom(50, 200);
    //                     clickX = device.width - offsetX;
    //                     clickY = offsetY;
    //                     coordinateClick(clickX, clickY, 500);
    //                     offsetX = getRandom(50, 200);
    //                     offsetY = getRandom(50, 200);
    //                     clickX = device.width - offsetX;
    //                     clickY = offsetY;
    //                     coordinateClick(clickX, clickY, 500);
    //                 }
    //             } else {
    //                 let randNum = getRandom(1, 10);
    //                 if (randNum > 7) {
    //                     coordinateClick(device.width / 2, device.height / 2, 2500);
    //                 } else if (randNum >= 7 && randNum < 9) {
    //                     coordinateClick(device.width / 2, device.height / 2, 1000);
    //                     coordinateClick(device.width / 2, device.height / 2, 1000);
    //                 }
    //             }

    //             let sure = textMatches(/(.*确定.*|.*确认.*)/).findOnce();
    //             if (sure != null) {
    //                 outputMessage('点击确定');
    //                 let sure_rect = sure.bounds();
    //                 click(sure_rect.centerX(), sure_rect.centerY());
    //                 sleep(3500);
    //             }
    //         }
    //     }

    //     checkAuthGranty();
    // } else {
    //     checkAuthGranty();
    // }

    return true;
}

function closeAdv() {
    outputMessage('检测关闭按钮');
    let close = className("android.widget.ImageView").visibleToUser(true).clickable(true).findOnce();
    let numClick = 10;
    while (numClick > 0) {
        numClick -= 1;
        close = className("android.widget.ImageView").visibleToUser(true).clickable(true).findOnce();
        if (close != null) {
            break;
        }
        sleep(1000);
    }
    if (close != null) {
        close.click();
        sleep(3000);
    }
}

/**
 * 检测权限
 */
function checkAuthGranty() {
    if (device.device == 'le_x620') { //乐视手机
        for (let i = 0; i < 5; i++) {
            sleep(2000);
            let widget = textStartsWith('允许').findOnce();
            if (widget != null) {
                widget.click();
                sleep(2000);
            }
        }
        for (let i = 0; i < 5; i++) {
            sleep(2000);
            let widget = textStartsWith('始终允许').findOnce();
            if (widget != null) {
                widget.click();
                sleep(2000);
            }
        }
    } else if (device.device == 'cereus' || device.device == 'ugg') { //小米6、红米note5
        for (let i = 0; i < 5; i++) {
            let widget = className("android.widget.Button").text('允许').findOnce();
            if (widget != null) {
                widget.click();
                sleep(1000);
            }
        }
    } else if (device.device == 'mido' || device.device == 'libra') {
        for (let i = 0; i < 8; i++) {
            let widget = textEndsWith('允许').findOnce();
            if (widget != null) {
                let widget_rect = widget.bounds();
                click(widget_rect.centerX(), widget_rect.centerY());
                sleep(4500);
            }
            sleep(800);
        }
    } else if (device.device == 'HWSLA-Q') {
        for (let i = 0; i < 8; i++) {
            let widget = textEndsWith('始终允许').findOnce();
            if (widget != null) {
                let widget_rect = widget.bounds();
                click(widget_rect.centerX(), widget_rect.centerY());
                sleep(4500);
            }
        }
    } else { //小米4c、 红米8a
        for (let i = 0; i < 5; i++) {
            let open = containText('正在尝试开启');
            if (open) {
                let widget = className("android.widget.Button").text('允许').findOnce();
                if (widget != null) {
                    widget.click();
                    sleep(1000);
                }
            }
        }
        for (let i = 0; i < 5; i++) {
            let permission = containText('访问以下权限');
            if (permission) {
                let widget = className("android.widget.Button").text('始终允许').findOnce();
                if (widget != null) {
                    widget.click();
                    sleep(1000);
                }
            }
        }
        for (let i = 0; i < 5; i++) {
            let widget = className("android.widget.Button").text('允许').findOnce();
            if (widget != null) {
                widget.click();
                sleep(1000);
            }
        }
    }
}

/**
 * 通过坐标点击屏幕
 * @param {*} x x坐标
 * @param {*} y y坐标
 * @param {*} duration 等待时长
 * @author guxiang
 */
function coordinateClick(x, y, duration) {
    click(x, y);
    sleep(duration);
    return;
}

/**
 * 获取设备信息
 * @author guxiang
 */
function deviceInfo() {
    let deviceId = device.getIMEI();
    if (deviceId == null) {
        deviceId = device.getAndroidId();
        // deviceId = android.provider.Settings.System.getString(
        //     context.getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
    }
    return '?phoneCode=' + deviceId + '&version=' + APP_VERSION + '&phoneType=' + device.device;
}

/**
 * 上报服务器
 * @author guxiang
 */
function notify(missionId, type) {
    try {
        let url = REPORT_URL + deviceInfo() + "&taskLogId=" + missionId + "&type=" + type;
        let res = http.get(url);
        if (res.statusCode == 200) {
            let resp = JSON.parse(res.body.string());
            if (resp.code == '10000') {
                doneTaskTotal = resp.data.doneTaskTotal;
            }
        }
    } catch (e) {
        return;
    }
}

/**
 * 点击广告上报服务器
 * @param {*} type
 * @param {*} adType
 */
function clickNotify(type, adType) {
    let url = CLICK_REPORT_URL + "?type=" + type + "&adType=" + adType + "&appName=" + AppName;
    http.get(url);
}

/**
 * 多次失败到达重试上限、通知服务器
 * @param {string} missionId 任务ID
 */
function failNotify(missionId) {
    let url = FAIL_URL + deviceInfo() + "&taskLogId=" + missionId;
    http.get(url);
}

/**
 * 随机获取数组的元素
 * @param {*} arr 容器数组
 * @author guxiang
 */
function randomArrItem(arr) {
    return arr[Math.floor(Math.random() * arr.length)];
}

/**
 * 判断场景加载是否成功
 * @param {*} activeName 场景名称
 * @author guxiang
 */
function checkActiveLoading(activeName, flag) {
    let act = currentActivity();
    if (act != activeName) {
        if (flag) {
            console.warn(activeName + ' wrong act...', act);
        }
        sleep(3000); //再等待3秒
        act = currentActivity();
        if (act != activeName) {
            if (flag) {
                console.warn(activeName + ' wrong act...', act);
            }
            sleep(3000);
            if (act != activeName) {
                if (flag) {
                    console.warn(activeName + ' wrong act...', act);
                }
                return false;
            }
        }
        if (flag) {
            console.info(activeName + ' mission continue...');
        }
    }
    return true;
}

function loopForActivity(num, activity, period) {
    let result = false;
    for (let i = 0; i < num; i++) {
        let act = currentActivity();
        if (dimPattern(act, activity)) {
            result = true;
            break;
        } else {
            sleep(period);
        }
    }
    return result;
}

function loopForWidget(num, period) {
    let result = false;
    for (let i = 0; i < num; i++) {
        let skip = textMatches(/(.*跳.*|.*过.*)/).findOnce();
        if (skip != null) {
            result = true;
            break;
        } else {
            sleep(period);
        }
    }
    return result;
}

//多次执行函数
function doMuliFun(func, n, args) {
    for (let i = 0; i < n; i++) {
        sleep(3000);
        func.call(this, args);
    }
}

/**
 * 通过ID找控件，3秒找不到返回null,找到就点击
 * @param {string} elm_id 控件ID
 */
function findOneByIdAndClick(elm_id) {
    let el = id(elm_id).clickable(true).findOnce();
    if (el) {
        el.click();
        return true;
    } else {
        sleep(2000);
        el = id(elm_id).clickable(true).findOnce();
        if (el) {
            el.click();
            return true;
        } else {
            return false;
        }
    }
}

/**
 * 通过className找到控件并点击
 * @param {string} class_name 
 */
function findOneByClassNameAndClick(class_name) {
    let el = className(class_name).clickable(true).findOnce();
    if (el != null) {
        el.click();
        return true;
    } else {
        sleep(2000);
        el = className(class_name).clickable(true).findOnce();
        if (el) {
            el.click();
            return true;
        } else {
            return false;
        }
    }
}

/**
 * 判断控件是否存在ByID
 * @param {string} elm_id 控件ID
 */
function checkExistsById(elm_id) {
    let el = id(elm_id).findOnce();
    if (el) {
        return true;
    } else {
        for (let i = 0; i < 3; i++) {
            sleep(1000);
            el = id(elm_id).findOnce();
            if (el != null) break;
        }
        if (el) {
            return true;
        } else {
            return false;
        }
    }
}

/**
 * 判断可点击控件是否存在
 * @param {string} class_name 
 */
function checkExistsByClassName(class_name) {
    let el = className(class_name).findOnce();
    if (el) {
        return true;
    } else {
        for (let i = 0; i < 3; i++) {
            sleep(1000);
            el = className(class_name).findOnce();
            if (el != null) break;
        }
        if (el) {
            return true;
        } else {
            return false;
        }
    }
}

/**
 * 判断控件是否存在
 * @param {*} widgetName 
 * @author guxiang 
 */
function checkWidget(widgetName) {
    let widget = className("android.widget.TextView").text(widgetName).findOnce();
    if (widget == null) {
        return false;
    } else {
        return true;
    }
}

/**
 * 
 * @param {*} context 
 */
function containText(context) {
    let ret = textContains(context).findOnce();
    if (ret == null) {
        for (let i = 0; i < 2; i++) {
            sleep(1000);
            ret = textContains(context).findOnce();
            if (ret != null) break;
        }
        if (ret != null) {
            return true;
        } else {
            return false;
        }
    } else {
        return true;
    }
}

/**
 * 获取适配应用的坐标
 * @param {*} appName 
 * @author guxiang
 */
function getFitCoordinate(appName) {
    let width = device.width;
    let height = device.height;
    if (appName == "抖音短视频") {
        if (width == 540 && height == 1200) {
            return coord.douyin.device_540_1200;
        } else if (width == 720 && height == 1520) {
            return coord.douyin.device_720_1520;
        } else if (width == 1080 && height == 1920) {
            return coord.douyin.device_1080_1920;
        } else if (width == 1080 && height == 2160) {
            return coord.douyin.device_1080_2160;
        }
    }
    return null;
}

function getPointByBL(w, h) {
    let p = {};
    p.x = device.width * w;
    p.y = device.height * h;
    return p;
}

/**
 * 在控制台输出
 * @param {string} context 
 */
function outputMessage(context) {
    console.info(context);
}

/**
 * 杀死最近运行的所有进程
 */
function killAllProgress() {
    if (device.device == 'le_x6') { //乐视手机
        home();
        sleep(4000);
        recents();
        sleep(5000);
        let clearButton = className('android.widget.ImageButton').findOnce();
        if (clearButton != null) {
            let clearRect = clearButton.bounds();
            click(clearRect.centerX(), clearRect.centerY());
        } else {
            sleep(2000);
            clearButton = className('android.widget.ImageButton').findOnce();
            if (clearButton != null) {
                let clearRect = clearButton.bounds();
                click(clearRect.centerX(), clearRect.centerY());
            } else {
                for (let i = 0; i < 10; i++) {
                    let button = swipeAndFind();
                    if (button) {
                        let widget = id('button').findOnce();
                        sleep(2000);
                        widget.click();
                        break;
                    }
                }
            }
        }

    } else if (device.device == 'le_x620') { //乐视手机
        home();
        sleep(4000);
        recents();
        sleep(5000);
        let clearButton = className('android.widget.ImageButton').findOnce();
        if (clearButton != null) {
            let clearRect = clearButton.bounds();
            click(clearRect.centerX(), clearRect.centerY());
        } else {
            back();
        }
    } else if (device.device == 'R9s' || device.device == 'R11' || device.device == 'R9sk') { //oppo R9s手机, oppoR11
        home();
        sleep(4000);
        recents();
        sleep(2000);
        let button = id("clear_button").clickable(true).findOnce();
        if (button != null) {
            button.click();
        } else {
            sleep(2000);
            button = id("clear_button").clickable(true).findOnce();
            if (button != null) {
                button.click();
            } else {
                back();
            }
        }
    } else if (device.device == 'HWSLA-Q') { //华为畅想
        home();
        sleep(4000);
        recents();
        sleep(2000);
        let clear = id('recent_igmbutton_clear_all').findOnce();
        if (clear != null) {
            let rect_clear = clear.bounds();
            coordinateClick(rect_clear.centerX(), rect_clear.centerY(), 3500);
        } else {
            back();
        }
    } else { //小米系列手机
        home();
        sleep(4000);
        recents();
        let button = idEndsWith(':id/clearAnimView').findOnce();
        if (button != null) {
            button.click();
        } else {
            sleep(2000);
            button = idEndsWith(':id/clearAnimView').findOnce();
            if (button != null) {
                button.click();
            } else {
                back();
            }
        }
    }
    sleep(1500);
}

/**
 * 心跳通知
 * @author guxiang
 */
function heartbeat() {
    let url = HEARTBEAT_URL + deviceInfo();
    //发起网络请求
    http.get(url);
}

/**
 * 划动屏幕寻找控件
 */
function swipeAndFind() {
    let start_x = device.width / 2;
    let start_y = device.height / 2;
    let end_x = device.width / 2;
    let end_y = device.height;

    gesture(300, [start_x, start_y], [end_x, end_y]);
    sleep(2000);
    let button = id('button').findOnce();
    if (button != null) {
        return true;
    } else {
        return false;
    }
}


/**
 * 自动挂机
 * @param {*} taskName 应用名称
 * @param {*} videoNum 视频次数
 * @param {*} insertScreenNum 插屏次数
 * @param {*} videoClickRate 视屏点击率
 * @param {*} insertScreenRate 插屏点击率
 * @param {*} fixedRate 信息流点击率
 * @param {*} startTime 
 * @param {*} endTime 
 * @param {*} taskLogId 任务ID
 */
function start(taskName, videoNum, insertScreenNum, videoClickRate, insertScreenRate, fixedRate, openScreenRate, startTime, endTime, eVideoClickRate, eInsertScreenRate, taskLogId, idx, videoStartTime, videoEndTime, link, downloadName, missionType, realApp, packageName) {
    outputMessage('应用名称: ' + taskName);
    outputMessage('设备信息: ' + device.device);
    outputMessage('安卓版本: ' + device.release);
    //清空后台
    killAllProgress();

    AppName = taskName;
    if (missionType != 1) {
        //上次任务和本次不是同一个APP名，并且上次任务不为空，执行机型伪装，否则跳过机型伪装
        outputMessage('上次任务: ' + lastApp);
        outputMessage('本次任务: ' + AppName);
        if (lastApp != AppName) {
            let ran = Math.random() * 100;
            //70%的概率更换设备信息
            if (ran <= 70) {
                outputMessage('更换设备信息');
                updateDeviceInfo(AppName);
            } else {
                //机型伪装
                protectDevice(AppName);
            }
        }
    }
    killAllProgress();

    //连接VPN
    connectDongtaiIp();

    let apkName = app.getAppName(packageName);
    if (apkName != null) {
        outputMessage('当前app主体版本: ' + apkName);
    } else {
        outputMessage(AppName + ' 未安装');
        throw new Error(AppName + ' 未安装');
    }

    //当app已经更新至最新版本，但是服务器又下发更新任务时，提交任务更新成功的通知
    if (missionType == 1) {
        //提交更新任务结束
        notify(taskLogId, 'upd');
    } else {
        let appExist = app.getPackageName(taskName);
        //没有安装这款app分身，去制作分身
        if (appExist == null) {
            updateDeviceInfo(taskName);
            sleep(5500);
        }

        if (!loadingApp(taskName, idx, openScreenRate)) {
            throw new Error('打开 ' + taskName + ' 失败');
        }
        outputMessage('视频次数: ' + videoNum + ' 插屏次数: ' + insertScreenNum);
        video_pro = videoClickRate * 100;
        cha_pro = insertScreenRate * 100;
        tencent_video_pro = eVideoClickRate * 100;
        tencent_cha_pro = eInsertScreenRate * 100;
        vStart = startTime;
        vEnd = endTime;
        //随机等待一定时间开始工作
        outputMessage('随机等待');
        let timer = getRandom(20, 25);
        timingWheel(timer);
        
        //循环执行看视频
        doMuliFun(clickVideo, videoNum, taskLogId);
        //循环执行看插屏
        //doMuliFun(clickInterAd, insertScreenNum, taskLogId);
        //点击信息流广告
        //clickInformationAdv(fixedRate, taskName);
        //彻底关闭分身
        killApp(taskName);
    }
    //任务正常完成回到桌面
    home();
}

/**
 * 点击开屏广告
 * @param {float} openScreenRate 点击概率
 */
function clickSplash() {
    //开屏广告关闭按钮
    sleep(10000);
    let screenClose = id(splash_close_id).findOnce();
    if (screenClose != null) {
        outputMessage('点击开频广告');
        //点击屏幕正中间
        let p = getPointByBL(0.5, 0.5);
        coordinateClick(p.x, p.y, 5000);
        //返回游戏
        app.launchApp(AppName);
        //检测下载
        deleteDownload();
        //寻找关闭按钮
        let btn = id(splash_close_id).findOnce();
        if (btn != null) {
            btn.click();
        } else {
            sleep(2000);
            btn = id(splash_close_id).findOnce();
            if (btn != null) {
                btn.click();
            } else {
                let act = currentActivity();
                if (act != Game_Activity) {
                    throw new Error('找不到关闭按钮');
                }
            }
        }
    }
}

/**
 * 保护设备信息
 */
function protectDevice(AppName) {
    //修改虚拟定位
    moveLocation(AppName);
    sleep(3000);
}

/**
 * 观看插屏广告
 * @param {object} args 自定义对象
 */
function clickInterAd(taskLogId) {
    heartbeat();
    sleep(5000);
    if (checkActivityByWidget('id', ':id/button_choujiang', null, false)) {
        outputMessage('看插屏广告');
        let interButton = idEndsWith('button_choujiang').findOnce();
        if (interButton != null) {
            let interRect = interButton.bounds();
            coordinateClick(interRect.centerX(), interRect.centerY(), 3500);
        }
        //通知服务器看一次插屏成功
        notify(taskLogId, 'insertScreen');
        let act = currentActivity();
        if (act == Dialog || dimPattern(act, 'MaterialDialog')) { //如果有弹窗场景，认为插屏弹出了
            outputMessage('弹出了插屏广告');
            sleep(5000);
            let ran = Math.random() * 100;
            // 点击广告
            if (ran < tencent_video_pro) {
                outputMessage('点击插屏广告');
                //点击广告位
                click(device.width / 2, device.height / 2);
                sleep(1500);
                //检测是否有下载
                deleteDownload();
                outputMessage('后退一下');
                back();
                sleep(2500);
                //不在app内 打开app
                if (!checkActivityByWidget('id', ':id/button_choujiang', null, false)) {
                    app.launchApp(AppName);
                    sleep(4500);
                }
            } else {
                //返回游戏
                let layout = className("android.widget.FrameLayout").findOne(2000);
                let closes = layout.find(className("android.widget.ImageView"));
                if (closes.length > 0) {
                    for (let i = 0; i < closes.length; i++) {
                        let close = closes[i];
                        let id = close.id();
                        if (dimPattern(id, 'jhsdk_csj_interstitial_btn_close')) {
                            outputMessage('A类关闭');
                            let close_rect = close.bounds();
                            click(close_rect.centerX(), close_rect.centerY());
                        } else {
                            if (i == 1) {
                                outputMessage('B类关闭');
                                let close_rect = close.bounds();
                                click(close_rect.centerX(), close_rect.centerY());
                            }
                        }
                    }
                } else {
                    if (device.device == 'le_x620') { //乐视
                        outputMessage('C类关闭');
                        coordinateClick(948, 233, 3000);
                        if (!checkActivityByWidget('id', ':id/button_choujiang', null, false)) { //没关掉，换个位置再关一次
                            outputMessage('D类关闭');
                            coordinateClick(924, 683, 3000);
                        }
                    } else if (device.device == 'mido') { //红米note
                        outputMessage('C类关闭');
                        coordinateClick(949, 237, 4000);
                        if (!checkActivityByWidget('id', ':id/button_choujiang', null, false)) { //没关掉，换个位置再关一次
                            outputMessage('D类关闭');
                            coordinateClick(963, 787, 3000);
                        }
                    } else if (device.device == 'libra') { // 小米4x
                        outputMessage('C类关闭');
                        coordinateClick(954, 237, 4000);
                        if (!checkActivityByWidget('id', ':id/button_choujiang', null, false)) { //没关掉，换个位置再关一次
                            outputMessage('D类关闭');
                            coordinateClick(954, 777, 3000);
                        }
                    } else if (device.device == 'HWSLA-Q') { //华为畅想7
                        outputMessage('C类关闭');
                        coordinateClick(631, 121, 4000);
                        if (!checkActivityByWidget('id', ':id/button_choujiang', null, false)) { //没关掉，换个位置再关一次
                            outputMessage('D类关闭');
                            coordinateClick(636, 493, 3000);
                        }
                    }
                }
            }
        } else { //错误的场景值，插屏播放失败
            outputMessage('没检测到插屏广告');
        }
    } else {
        throw new Error('插屏场景错误');
    }
}

/**
 * 观看视频广告
 * @param {object} args 自定义对象
 */
function clickVideo(taskLogId) {
    heartbeat();
    sleep(5000);

    //检测VPN IP是否和请求IP 保持一致
    // if (!checkVpnIp()) throw new Error('VPN IP 和请求IP 不一致');

    outputMessage('点击率: ' + video_pro.toFixed(2));
    if (checkActivityByWidget('id', ':id/button_guaji', null, true)) {
        outputMessage('看视频广告');
        let videoButton = idEndsWith(':id/button_guaji').findOnce();
        if (videoButton != null) {
            let buttonOffsetX = getRandom(5, 200);
            let buttonOffsetY = getRandom(5, 45);
            let videoRect = videoButton.bounds();
            let buttonClickX = videoRect.centerX() + buttonOffsetX;
            let buttonClickY = videoRect.centerY() + buttonOffsetY;
            coordinateClick(buttonClickX, buttonClickY, 3500);
        } else {
            throw new Error('找不到视频播放按钮');
        }
        //通知服务器看一次视频成功
        notify(taskLogId, 'video');
        sleep(3500);
        let act = currentActivity();
        if (checkActivity(act, RewardvideoPortraitADActivity) || checkActivity(act, FrameLayout) || checkActivity(act, LinearLayout)) {
            //直接杀掉进程
            let exitRand = Math.random() * 100;
            //中途退出概率3%
            if (exitRand < 3 && video_pro != 100) {
                outputMessage('中途退出');
                let exitSleep = getRandom(1, 5);
                sleep(exitSleep * 1000);
                throw new Error('中途退出');
            }
            let ran = Math.random() * 100;

            if (ran < video_pro) { //点击逻辑
                outputMessage('准备点击');
                let close = className("android.widget.ImageView").visibleToUser(true).clickable(true).findOnce();
                let numClick = 35;
                while (numClick > 0) {
                    numClick -= 1;
                    close = className("android.widget.ImageView").visibleToUser(true).clickable(true).findOnce();
                    if (close != null) {
                        let willSend = textMatches(/(.*奖励将于.*)/).findOnce();
                        if (willSend != null) { //找到的是音量开关按钮，奖励还没发出，什么也不做

                        } else {
                            let alreadySend = textMatches(/(.*恭喜获得奖励.*)/).findOnce();
                            if (alreadySend != null) { //是关闭按钮
                                let seedRand = getRandom(1, 10);
                                if (seedRand > 2) {
                                    close.click();
                                    let randSleep = getRandom(1, 3);
                                    sleep(randSleep * 1000);
                                }
                                break;
                            } else {
                                if (numClick < 5) {
                                    break;
                                }
                            }
                        }
                    }
                    sleep(1000);
                }
                if (close != null) {
                    close = className("android.widget.ImageView").visibleToUser(true).clickable(true).findOnce();
                    //点击广告位
                    outputMessage('点击广告位');
                    let download = textMatches(/(.*下载.*|.*打开.*|.*领取.*|.*安装.*)/).findOnce();
                    if (download != null) {
                        let downloadRand = getRandom(1, 100);
                        if (downloadRand < 80) {
                            let clickX = getRandom(402, 681);
                            let clickY = getRandom(1179, 1386);
                            let randSeed = getRandom(1, 10);
                            if (randSeed < 3) {
                                clickX = getRandom(30, 166);
                                clickY = getRandom(171, 248);
                            } else if (randSeed >= 3 && randSeed < 5) {
                                clickX = getRandom(10, 30);
                                clickY = getRandom(18, 183);
                            }
                            if (device.device == 'HWSLA-Q') {
                                clickX = getRandom(262, 493);
                                clickY = getRandom(743, 902);
                                if (randSeed < 3) {
                                    clickX = getRandom(30, 105);
                                    clickY = getRandom(136, 171);
                                } else if (randSeed >= 3 && randSeed < 5) {
                                    clickX = getRandom(10, 30);
                                    clickY = getRandom(31, 142);
                                }
                            }
                            if (device.device == 'le_x620') {
                                clickX = getRandom(383, 728);
                                clickY = getRandom(1061, 1305);
                                if (randSeed < 3) {
                                    clickX = getRandom(180, 240);
                                    clickY = getRandom(61, 143);
                                } else if (randSeed >= 3 && randSeed < 5) {
                                    clickX = getRandom(50, 156);
                                    clickY = getRandom(185, 294);
                                }
                            }
                            coordinateClick(clickX, clickY, 2500);
                            closeAdv();
                            closeAdv();
                        } else {
                            let offsetX = getRandom(10, 35);
                            let offsetY = getRandom(10, 35);
                            let download_rect = download.bounds();
                            let clickX = download_rect.centerX() + offsetX;
                            let clickY = download_rect.centerY() + offsetY;
                            coordinateClick(clickX, clickY, 2500);
                            closeAdv();
                            closeAdv();
                        }
                    } else {
                        let clickX = getRandom(225, 283);
                        let clickY = getRandom(121, 279);
                        if (device.device == 'HWSLA-Q') {
                            clickX = getRandom(162, 222);
                            clickY = getRandom(62, 136);
                        }
                        if (device.device == 'le_x620') {
                            clickX = getRandom(366, 822);
                            clickY = getRandom(1166, 1805);
                        }
                        coordinateClick(clickX, clickY, 2500);
                        closeAdv();
                        closeAdv();
                    }
                }
            } else { //正常关闭
                let reward = textMatches(/(.*奖励将于.*)/).findOne(8000);
                //双关闭
                if (reward != null) {
                    outputMessage('双关闭');
                    let closeText = textStartsWith("恭喜获得奖励").findOnce();
                    let closeNum = 45;
                    while (closeNum > 0) {
                        closeNum -= 1;
                        closeText = textStartsWith("恭喜获得奖励").findOnce();
                        if (closeText != null) {
                            break;
                        }
                        sleep(1000);
                    }
                    if (closeText != null) {
                        let closeOne = className("android.widget.ImageView").visibleToUser(true).clickable(true).findOnce();
                        let numOne = 10;
                        while (numOne > 0) {
                            numOne -= 1;
                            closeOne = className("android.widget.ImageView").visibleToUser(true).clickable(true).findOnce();
                            if (closeOne != null) {
                                break;
                            }
                            sleep(1000);
                        }
                        if (closeOne != null) {
                            let missRand = getRandom(1, 100);
                            if (missRand < 6) {
                                outputMessage('模拟误触');
                                let closeOneRect = closeOne.bounds();
                                let downloadRand = getRandom(1, 100);
                                let offsetX = getRandom(50, 70);
                                let offsetY = getRandom(50, 70);
                                if (device.device == 'HWSLA-Q') {
                                    offsetX = getRandom(40, 55);
                                    offsetY = getRandom(40, 55);
                                }
                                if (downloadRand < 25) {
                                    let clickX = closeOneRect.centerX() + offsetX;
                                    let clickY = closeOneRect.centerY() + offsetY;
                                    if (clickX < device.width && clickY < device.height) {
                                        coordinateClick(clickX, clickY, 2500);
                                        closeAdv();
                                    }
                                } else if (downloadRand >= 25 && downloadRand < 50) {
                                    let clickX = closeOneRect.centerX() + offsetX;
                                    let clickY = closeOneRect.centerY() - offsetY;
                                    if (clickX < device.width && clickY > 0) {
                                        coordinateClick(clickX, clickY, 2500);
                                        closeAdv();
                                    }
                                } else if (downloadRand >= 50 && downloadRand < 75) {
                                    let clickX = closeOneRect.centerX() - offsetX;
                                    let clickY = closeOneRect.centerY() + offsetY;
                                    if (clickX > 0 && clickY < device.height) {
                                        coordinateClick(clickX, clickY, 2500);
                                        closeAdv();
                                    }
                                } else if (downloadRand >= 75 && downloadRand < 100) {
                                    let clickX = closeOneRect.centerX() - offsetX;
                                    let clickY = closeOneRect.centerY() - offsetY;
                                    if (clickX > 0 && clickY > 0) {
                                        coordinateClick(clickX, clickY, 2500);
                                        closeAdv();
                                    }
                                }
                                throw new Error('误触');
                            }
                            let closeDoubleRand = getRandom(1, 3);
                            sleep(closeDoubleRand * 1000);

                            let closeOneOffset = closeOne.bounds();
                            let oneRandOffset = getRandom(1, 100);
                            let offsetX = getRandom(10, 30);
                            let offsetY = getRandom(10, 30);
                            if (device.device == 'HWSLA-Q') {
                                offsetX = getRandom(10, 30);
                                offsetY = getRandom(10, 30);
                            }
                            if (oneRandOffset < 25) {
                                let clickX = closeOneOffset.centerX() + offsetX;
                                let clickY = closeOneOffset.centerY() + offsetY;
                                if (clickX < device.width && clickY < device.height) {
                                    outputMessage('关闭位1');
                                    coordinateClick(clickX, clickY, 2500);
                                }
                            } else if (oneRandOffset >= 25 && oneRandOffset < 50) {
                                let clickX = closeOneOffset.centerX() + offsetX;
                                let clickY = closeOneOffset.centerY() - offsetY;
                                if (clickX < device.width && clickY > 0) {
                                    outputMessage('关闭位1');
                                    coordinateClick(clickX, clickY, 2500);
                                }
                            } else if (oneRandOffset >= 50 && oneRandOffset < 75) {
                                let clickX = closeOneOffset.centerX() - offsetX;
                                let clickY = closeOneOffset.centerY() + offsetY;
                                if (clickX > 0 && clickY < device.height) {
                                    outputMessage('关闭位1');
                                    coordinateClick(clickX, clickY, 2500);
                                }
                            } else if (oneRandOffset >= 75 && oneRandOffset < 100) {
                                let clickX = closeOneOffset.centerX() - offsetX;
                                let clickY = closeOneOffset.centerY() - offsetY;
                                if (clickX > 0 && clickY > 0) {
                                    outputMessage('关闭位1');
                                    coordinateClick(clickX, clickY, 2500);
                                }
                            }

                            sleep(1500);
                            let closeTwo = className("android.widget.ImageView").visibleToUser(true).clickable(true).findOnce();
                            let numTwo = 10;
                            while (numTwo > 0) {
                                numTwo -= 1;
                                closeTwo = className("android.widget.ImageView").visibleToUser(true).clickable(true).findOnce();
                                if (closeTwo != null) {
                                    break;
                                }
                                sleep(1000);
                            }
                            if (closeTwo != null) {
                                let missRandTwo = getRandom(1, 100);
                                if (missRandTwo < 6) {
                                    outputMessage('模拟误触');
                                    let closeTwoRect = closeTwo.bounds();
                                    let downloadRand = getRandom(1, 100);
                                    let offsetX = getRandom(50, 70);
                                    let offsetY = getRandom(50, 70);
                                    if (device.device == 'HWSLA-Q') {
                                        offsetX = getRandom(40, 55);
                                        offsetY = getRandom(40, 55);
                                    }
                                    if (downloadRand < 25) {
                                        let clickX = closeTwoRect.centerX() + offsetX;
                                        let clickY = closeTwoRect.centerY() + offsetY;
                                        if (clickX < device.width && clickY < device.height) {
                                            coordinateClick(clickX, clickY, 2500);
                                            closeAdv();
                                        }
                                    } else if (downloadRand >= 25 && downloadRand < 50) {
                                        let clickX = closeTwoRect.centerX() + offsetX;
                                        let clickY = closeTwoRect.centerY() - offsetY;
                                        if (clickX < device.width && clickY > 0) {
                                            coordinateClick(clickX, clickY, 2500);
                                            closeAdv();
                                        }
                                    } else if (downloadRand >= 50 && downloadRand < 75) {
                                        let clickX = closeTwoRect.centerX() - offsetX;
                                        let clickY = closeTwoRect.centerY() + offsetY;
                                        if (clickX > 0 && clickY < device.height) {
                                            coordinateClick(clickX, clickY, 2500);
                                            closeAdv();
                                        }
                                    } else if (downloadRand >= 75 && downloadRand < 100) {
                                        let clickX = closeTwoRect.centerX() - offsetX;
                                        let clickY = closeTwoRect.centerY() - offsetY;
                                        if (clickX > 0 && clickY > 0) {
                                            coordinateClick(clickX, clickY, 2500);
                                            closeAdv();
                                        }
                                    }
                                    throw new Error('误触');
                                }
                                let closeDoubleRandTwice = getRandom(1, 5);
                                sleep(closeDoubleRandTwice * 1000);

                                let closeTwoOffset = closeTwo.bounds();
                                let twoRandOffset = getRandom(1, 100);
                                let offsetX = getRandom(10, 30);
                                let offsetY = getRandom(10, 30);
                                if (device.device == 'HWSLA-Q') {
                                    offsetX = getRandom(10, 30);
                                    offsetY = getRandom(10, 30);
                                }
                                if (twoRandOffset < 25) {
                                    let clickX = closeTwoOffset.centerX() + offsetX;
                                    let clickY = closeTwoOffset.centerY() + offsetY;
                                    if (clickX < device.width && clickY < device.height) {
                                        outputMessage('关闭位2');
                                        coordinateClick(clickX, clickY, 2500);
                                    }
                                } else if (twoRandOffset >= 25 && twoRandOffset < 50) {
                                    let clickX = closeTwoOffset.centerX() + offsetX;
                                    let clickY = closeTwoOffset.centerY() - offsetY;
                                    if (clickX < device.width && clickY > 0) {
                                        outputMessage('关闭位2');
                                        coordinateClick(clickX, clickY, 2500);
                                    }
                                } else if (twoRandOffset >= 50 && twoRandOffset < 75) {
                                    let clickX = closeTwoOffset.centerX() - offsetX;
                                    let clickY = closeTwoOffset.centerY() + offsetY;
                                    if (clickX > 0 && clickY < device.height) {
                                        outputMessage('关闭位2');
                                        coordinateClick(clickX, clickY, 2500);
                                    }
                                } else if (twoRandOffset >= 75 && twoRandOffset < 100) {
                                    let clickX = closeTwoOffset.centerX() - offsetX;
                                    let clickY = closeTwoOffset.centerY() - offsetY;
                                    if (clickX > 0 && clickY > 0) {
                                        outputMessage('关闭位2');
                                        coordinateClick(clickX, clickY, 2500);
                                    }
                                }
                                sleep(1500);
                            }
                        }
                    } else {
                        let closeOne = className("android.widget.ImageView").visibleToUser(true).clickable(true).findOnce();
                        let numOne = 5;
                        while (numOne > 0) {
                            numOne -= 1;
                            closeOne = className("android.widget.ImageView").visibleToUser(true).clickable(true).findOnce();
                            if (closeOne != null) {
                                break;
                            }
                            sleep(1000);
                        }
                        if (closeOne != null) {
                            closeOne.click();
                            sleep(1500);
                        }
                    }
                } else { //单关闭
                    outputMessage('单关闭');
                    let checkButton = idEndsWith(':id/button_guaji').findOnce();
                    if (checkButton == null) { //不在首页主场景中了
                        let close = className("android.widget.ImageView").visibleToUser(true).clickable(true).findOnce();
                        let findNum = 55;
                        while (findNum > 0) {
                            findNum -= 1;
                            close = className("android.widget.ImageView").visibleToUser(true).clickable(true).findOnce();
                            if (close != null) {
                                outputMessage('找到了关闭按钮');
                                break;
                            }
                            sleep(1000);
                        }
                        if (close != null) {
                            let randSingleClose = getRandom(1, 5);
                            sleep(randSingleClose * 1000);
                            if (close != null) {
                                let randSingleClose = getRandom(1, 3);
                                sleep(randSingleClose * 1000);
    
                                let closeOneOffset = close.bounds();
                                let oneRandOffset = getRandom(1, 100);
                                let offsetX = getRandom(5, 15);
                                let offsetY = getRandom(5, 15);
                                if (device.device == 'HWSLA-Q') {
                                    offsetX = getRandom(5, 15);
                                    offsetY = getRandom(5, 15);
                                }
                                if (device.device == 'le_x620') {
                                    offsetX = getRandom(5, 15);
                                    offsetY = getRandom(5, 15);
                                }
                                if (oneRandOffset < 25) {
                                    let clickX = closeOneOffset.centerX() + offsetX;
                                    let clickY = closeOneOffset.centerY() + offsetY;
                                    if (clickX < device.width && clickY < device.height) {
                                        coordinateClick(clickX, clickY, 2500);
                                    }
                                } else if (oneRandOffset >= 25 && oneRandOffset < 50) {
                                    let clickX = closeOneOffset.centerX() + offsetX;
                                    let clickY = closeOneOffset.centerY() - offsetY;
                                    if (clickX < device.width && clickY > 0) {
                                        coordinateClick(clickX, clickY, 2500);
                                    }
                                } else if (oneRandOffset >= 50 && oneRandOffset < 75) {
                                    let clickX = closeOneOffset.centerX() - offsetX;
                                    let clickY = closeOneOffset.centerY() + offsetY;
                                    if (clickX > 0 && clickY < device.height) {
                                        coordinateClick(clickX, clickY, 2500);
                                    }
                                } else if (oneRandOffset >= 75 && oneRandOffset < 100) {
                                    let clickX = closeOneOffset.centerX() - offsetX;
                                    let clickY = closeOneOffset.centerY() - offsetY;
                                    if (clickX > 0 && clickY > 0) {
                                        coordinateClick(clickX, clickY, 2500);
                                    }
                                }
                            }
                        }
                    } else {
                        outputMessage('未进入视频场景');
                    }
                }
            }
            videoButton = idEndsWith(':id/button_guaji').findOnce();
            //没找到挂机按钮
            if (videoButton == null) {
                outputMessage('关闭位3');
                //尝试后退
                back();
            }
        } else {
            outputMessage('未知场景');
        }

        //获取随机视频间隔
        let interval = random(vStart, vEnd);
        outputMessage('间隔: ' + interval + ' 秒');
        sleep(interval * 1000);
    } else {
        throw new Error('找不到挂机按钮');
    }
}

/**
 * 点击视频广告
 * @param {number} width
 * @param {number} height
 * @param {object} close
 */
function userClickAd(width, height) {
    coordinateClick(width, height, 2000);
    //检测是否有下载
    deleteDownload();
    //检测是否有权限提示
    let ret = containText('正在尝试开启');
    if (ret) {
        let widget = className("android.widget.Button").text('允许').findOnce();
        if (widget != null) {
            widget.click();
            sleep(5000);
        } else {
            sleep(2000);
            widget = className("android.widget.Button").text('允许').findOnce();
            if (widget != null) {
                widget.click();
                sleep(5000);
            }
        }
    }
    let widget = className("android.widget.Button").text('同意并继续').findOnce();
    if (widget != null) {
        widget.click();
        sleep(5000);
    } else {
        sleep(2000);
        widget = className("android.widget.Button").text('同意并继续').findOnce();
        if (widget != null) {
            widget.click();
            sleep(5000);
        }
    }
    widget = className("android.widget.Button").text('退出').findOnce();
    if (widget != null) {
        widget.click();
        sleep(5000);
    } else {
        sleep(2000);
        widget = className("android.widget.Button").text('退出').findOnce();
        if (widget != null) {
            widget.click();
            sleep(5000);
        }
    }
    let act = currentActivity();
    if (!checkActivity(act, TT_Reward_Activity) && !checkActivity(act, Game_Activity) && !checkActivity(act, GDT_Reward_Activity)) { //退出了广告activity，说明打开了下载页面
        //跳回到游戏
        outputMessage('返回游戏');
        app.launchApp(AppName);
        sleep(5000);
        act = currentActivity();
        if (checkActivity(act, TT_Reward_Activity)) { //穿山甲
            findOneByIdAndClick(reward_close_id);
        } else if (checkActivity(act, GDT_Reward_Activity)) { //优量汇
            let close = className(GDT_reward_closd).clickable(true).findOnce();
            //等不到关闭按钮
            if (close == null) {
                sleep(5000);
                for (let i = 0; i < 5; i++) {
                    sleep(3000);
                    let closed_repeat = className(GDT_reward_closd).clickable(true).findOnce();
                    if (closed_repeat != null) {
                        close = closed_repeat;
                        break;
                    }
                }
            }
            if (close == null) {
                throw new Error('找不到关闭按钮');
            } else {
                let close_rect = close.bounds();
                click(close_rect.centerX(), close_rect.centerY());
                sleep(2000);
            }
        }
        return true;
    } else { //点击广告失败
        return false;
    }
}

/**
 * 点击插屏广告
 */
function userClickInterAd() {
    coordinateClick(device.width / 2, device.height / 2, 2000);
    //检测是否有下载
    deleteDownload();
    //检测权限
    let ret = containText('正在尝试开启');
    if (ret) {
        let widget = className("android.widget.Button").text('允许').findOnce();
        if (widget != null) {
            widget.click();
        } else {
            sleep(2000);
            widget = className("android.widget.Button").text('允许').findOnce();
            if (widget != null) {
                widget.click();
            }
        }
    }
    let widget = className("android.widget.Button").text('退出').findOnce();
    if (widget != null) {
        widget.click();
        sleep(2000);
    } else {
        sleep(2000);
        widget = className("android.widget.Button").text('退出').findOnce();
        if (widget != null) {
            widget.click();
            sleep(2000);
        }
    }
    let act = currentActivity();
    if (!checkActivity(act, Game_Activity)) {//退出了广告activity，说明打开了下载页面
        //跳回到游戏
        app.launchApp(AppName);
        sleep(3000);
        findOneByIdAndClick(insert_close_id);
    } else {//点击广告失败
        findOneByIdAndClick(insert_close_id);
    }
}

/**
 * 点击信息流广告
 * @param {float} 点击率 
 */
function clickInformationAdv(fixedRate) {
    //在游戏主界面、可以点击信息流广告
    let ran = Math.random() * 100;
    let rate = fixedRate * 100;
    //点击广告
    if (ran < rate) {
        outputMessage('点击信息流广告');
        //右上角坐标
        let p = getPointByBL(0.5, 0.1);
        coordinateClick(p.x, p.y, 2000);
        deleteDownload();
    }
}

/**
 * 停止应用下载
 */
function deleteDownload() {
    //oppo R11手机 无法兼容
    if (device.device == 'R11' || device.device == 'R9s') return;
    notifications();
    let widget = textContains('暂停').findOnce();
    if (widget == null) {
        sleep(2000);
        widget = textContains('暂停').findOnce();
    }
    if (widget != null) {
        let banner = widget.parent().parent().parent();
        banner.click();
        sleep(1500);
        let confirm = className("android.widget.Button").text("确定").findOnce();
        if (confirm != null) {
            confirm.click();
        } else {
            sleep(2000);
            confirm = className("android.widget.Button").text("确定").findOnce();
            if (confirm != null) {
                confirm.click();
            }
        }
    } else {
        if (device.device == 'le_x620') { //乐视手机
            let clear = textContains('全部清除').clickable(true).findOnce();
            if (clear != null) {
                clear.click();
            } else {
                sleep(2000);
                clear = textContains('全部清除').clickable(true).findOnce();
                if (clear != null) {
                    clear.click();
                } else {
                    back();
                }
            }
        } else if (device.device == 'libra' || device.device == 'cereus' || device.device == 'mido' || device.device == 'gemini') { //小米4c手机、小米6手机
            let clear = className('android.widget.ImageButton').clickable(true).findOnce();
            if (clear != null) {
                clear.click();
            } else {
                sleep(2000);
                clear = className('android.widget.ImageButton').clickable(true).findOnce();
                if (clear != null) {
                    clear.click();
                } else {
                    back();
                }
            }
        } else if (device.device == 'olivelite' || device.device == 'ugg') { //红米8a、红米note5
            let clear = className('android.view.View').clickable(true).findOnce();
            if (clear != null) {
                clear.click();
            } else {
                sleep(2000);
                clear = className('android.view.View').clickable(true).findOnce();
                if (clear != null) {
                    clear.click();
                } else {
                    back();
                }
            }
        } else {
            back();
        }
    }
    sleep(3000);
}

/**
 * 判断是否是需要的场景值
 * @param {string} actName 场景值
 */
function checkActivity(act, actName) {
    if (act == actName) {
        return true;
    } else {
        return false;
    }
}

/**
 * 格式化时间
 * @param {*} fmt 
 * @param {*} date 
 */
function dateFtt(fmt, date) {
    var o = {
        "M+": date.getMonth() + 1,     //月份 
        "d+": date.getDate(),     //日 
        "h+": date.getHours(),     //小时 
        "m+": date.getMinutes(),     //分 
        "s+": date.getSeconds(),     //秒 
        "q+": Math.floor((date.getMonth() + 3) / 3), //季度 
        "S": date.getMilliseconds()    //毫秒 
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

/**
 * 模糊检测场景值
 * @param {*} str 
 * @param {*} pattern 
 */
function dimPattern(str, pattern) {
    return str.indexOf(pattern) == -1 ? false : true;
}


/**
 * 通过控件信息判断场景值
 * @param {*} type 
 * @param {*} widget 
 * @param {*} keywords 
 */
function checkActivityByWidget(type, widget, keywords, isBack) {
    let result = false;
    if (type == 'text') {
        for (let i = 0; i < 10; i++) {
            sleep(800);
            result = textStartsWith(keywords).exists();
            if (result) break;
        }
    } else if (type == 'className') {
        for (let i = 0; i < 10; i++) {
            sleep(800);
            if (keywords != null) {
                result = className(widget).text(keywords).exists();
            } else {
                result = className(widget).exists();
            }
            if (result) break;
        }
    } else if (type == 'id') {
        for (let i = 0; i < 10; i++) {
            sleep(800);
            result = idEndsWith(widget).exists();
            outputMessage(widget + ' ' + result);
            if (result) break;
            if (isBack) back();
        }
    }

    return result;
}

/**
 * 打开apk包
 */
function openApk(filePath) {
    try {
        let exist = files.isFile(filePath);
        if (exist) {
            if (device.device == 'mido') { //小米4x
                let apkFile = new java.io.File(filePath);
                let intent = new Intent(Intent.ACTION_VIEW);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                let uri = FileProvider.getUriForFile(context, "com.leyou.phone.fileprovider", apkFile);
                intent.setDataAndType(uri, "application/vnd.android.package-archive");
                context.startActivity(intent);
            } else if (device.device == 'le_x620') { //乐视
                let apk = new java.io.File(filePath);
                let uri = android.net.Uri.fromFile(apk);
                let intent = new Intent();
                intent.setClassName("com.android.packageinstaller", "com.android.packageinstaller.PackageInstallerActivity");
                intent.setData(uri);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
            } else if (device.device == 'HWSLA-Q') {
                let apkFile = new java.io.File(filePath);
                let intent = new Intent(Intent.ACTION_VIEW);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                let uri = FileProvider.getUriForFile(context, "com.leyou.phone.fileprovider", apkFile);
                intent.setDataAndType(uri, "application/vnd.android.package-archive");
                context.startActivity(intent);
            } else if (device.device == 'libra') {
                let apkFile = new java.io.File(filePath);
                let intent = new Intent(Intent.ACTION_VIEW);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                let uri = FileProvider.getUriForFile(context, "com.leyou.phone.fileprovider", apkFile);
                intent.setDataAndType(uri, "application/vnd.android.package-archive");
                context.startActivity(intent);
            } else if (device.device == 'R11' || device.device == 'R9s') {
                let apk = new java.io.File(filePath);
                let uri = android.net.Uri.fromFile(apk);
                let intent = new Intent();
                intent.setClassName("com.android.packageinstaller", "com.android.packageinstaller.PackageInstallerActivity");
                intent.setData(uri);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
            } else if (device.device == 'cereus') {
                let apkFile = new java.io.File(filePath);
                let intent = new Intent(Intent.ACTION_VIEW);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                let uri = FileProvider.getUriForFile(context, "com.leyou.phone.fileprovider", apkFile);
                intent.setDataAndType(uri, "application/vnd.android.package-archive");
                context.startActivity(intent);
            } else {
                outputMessage('未适配的手机型号');
                return false;
            }
            return true;
        } else {
            return false;
        }
    } catch (e) {
        outputMessage('安装apk异常' + e);
        return false;
    }
}

/**
 * 下载apk包
 */
function downloadApk(path, name) {
    try {
        let url = new java.net.URL(path);
        let urlConn = url.openConnection();
        urlConn.setRequestMethod("GET");
        urlConn.setDoOutput(true);
        urlConn.connect();

        let inputStream = urlConn.getInputStream();
        let file = new java.io.File('/sdcard/Download/');
        let outputFile = new java.io.File(file, name);
        let outStream = new java.io.FileOutputStream(outputFile);

        let buffer = util.java.array('byte', 256);
        let len = 0;
        while ((len = inputStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }

        outStream.flush();
        outStream.close();
        inputStream.close();

        return true;
    } catch (e) {
        outputMessage('下载apk失败:' + e)
        return false;
    }
}

/**
 * 安装app
 */
function installApk() {
    if (device.device == 'mido') {
        let button = textStartsWith('安装').findOnce();
        if (button != null) {
            let button_rect = button.bounds();
            click(button_rect.centerX(), button_rect.centerY());
            sleep(15000);
        } else {
            button = textStartsWith('继续安装').findOnce();
            if (button != null) {
                let button_rect = button.bounds();
                click(button_rect.centerX(), button_rect.centerY());
                sleep(15000);
            }
        }
    } else if (device.device == 'le_x620') {
        let button = textEndsWith('安装').findOnce();
        if (button != null) {
            let button_rect = button.bounds();
            click(button_rect.centerX(), button_rect.centerY());
            sleep(3500);
            let next = textEndsWith('下一步').findOnce();
            if (next != null) {
                let next_rect = next.bounds();
                click(next_rect.centerX(), next_rect.centerY());
                sleep(5500);
                let install = textEndsWith('安装').findOnce();
                if (install != null) {
                    let install_rect = install.bounds();
                    click(install_rect.centerX(), install_rect.centerY());
                    sleep(15000);
                } else {
                    outputMessage('找不到安装');
                }
            } else {
                outputMessage('找不到下一步');
            }
        } else {
            let next = textEndsWith('下一步').findOnce();
            if (next != null) {
                let next_rect = next.bounds();
                click(next_rect.centerX(), next_rect.centerY());
                sleep(5500);
                let install = textEndsWith('安装').findOnce();
                if (install != null) {
                    let install_rect = install.bounds();
                    click(install_rect.centerX(), install_rect.centerY());
                    sleep(15000);
                } else {
                    outputMessage('找不到安装');
                }
            }
        }
    } else if (device.device == 'HWSLA-Q') {
        let known = textEndsWith('官方推荐').findOnce();
        if (known != null) {
            click(65, 1042);
            sleep(4500);
            let next = textEndsWith('继续安装').findOnce();
            if (next != null) {
                let next_rect = next.bounds();
                click(next_rect.centerX(), next_rect.centerY());
                sleep(15000);
            }
        } else {
            let install = textEndsWith('安装').findOnce();
            if (install != null) {
                let install_rect = install.bounds();
                click(install_rect.centerX(), install_rect.centerY());
                sleep(15000);
            } else {
                outputMessage('找不到安装');
            }
        }
    } else if (device.device == 'libra') {
        let button = textStartsWith('安装').findOnce();
        if (button != null) {
            let button_rect = button.bounds();
            click(button_rect.centerX(), button_rect.centerY());
            sleep(15000);
        }
    }
}

/**
 * 开关飞行模式
 */
function switchFlyMod() {
    killAllProgress();
    outputMessage('切换网络接入点');
    if (device.device == 'le_x620') {
        let openRet = app.launchApp('设置');
        if (!openRet) throw new Error('打开设置失败');
        sleep(3500);
        let more = textStartsWith('SIM 卡').findOnce();
        if (more != null) {
            let more_rect = more.bounds();
            click(more_rect.centerX(), more_rect.centerY());
            sleep(3500);
            let config = textStartsWith('SIM 卡 1 设置').findOnce();
            if (config != null) {
                let config_rect = config.bounds();
                click(config_rect.centerX(), config_rect.centerY());
                sleep(3500);
                let apn = textStartsWith('接入点名称 (APN)').findOnce();
                if (apn != null) {
                    let apn_rect = apn.bounds();
                    click(apn_rect.centerX(), apn_rect.centerY());
                    sleep(3500);
                    let button = className('android.widget.RadioButton').clickable(true).checked(false).findOnce();
                    if (button != null) {
                        button.click();
                        sleep(12000);
                        button = className('android.widget.RadioButton').clickable(true).checked(false).findOnce();
                        if (button != null) {
                            button.click();
                            sleep(5500);
                        } else {
                            throw new Error('APN 接入点设置错误');
                        }
                    } else {
                        //无法切换ip, 逻辑停止
                        throw new Error('APN 接入点设置错误');
                    }
                } else {
                    throw new Error('APN 接入点设置错误');
                }
            } else {
                throw new Error('APN 接入点设置错误');
            }
        } else {
            throw new Error('APN 接入点设置错误');
        }
    } else if (device.device == 'mido') {
        let openRet = app.launchApp('设置');
        if (!openRet) throw new Error('打开设置失败');
        sleep(3500);
        let more = textStartsWith('双卡和移动网络').findOnce();
        if (more != null) {
            let more_rect = more.bounds();
            click(more_rect.centerX(), more_rect.centerY());
            sleep(3500);
            let config = textStartsWith('中国联通').findOnce();
            if (config != null) {
                let config_rect = config.bounds();
                click(config_rect.centerX(), config_rect.centerY());
                sleep(3500);
                let apn = textStartsWith('接入点名称 (APN)').findOnce();
                if (apn != null) {
                    let apn_rect = apn.bounds();
                    click(apn_rect.centerX(), apn_rect.centerY());
                    sleep(4500);
                    coordinateClick(559, 580, 12000);
                    coordinateClick(559, 790, 5500);
                } else {
                    throw new Error('APN 接入点设置错误');
                }
            } else {
                throw new Error('APN 接入点设置错误');
            }
        } else {
            throw new Error('APN 接入点设置错误');
        }
    } else if (device.device == 'libra') {
        let openRet = app.launchApp('设置');
        if (!openRet) throw new Error('打开设置失败');
        sleep(3500);
        let more = textStartsWith('双卡和移动网络').findOnce();
        if (more != null) {
            let more_rect = more.bounds();
            click(more_rect.centerX(), more_rect.centerY());
            sleep(3500);
            let config = textStartsWith('中国联通').findOnce();
            if (config != null) {
                let config_rect = config.bounds();
                click(config_rect.centerX(), config_rect.centerY());
                sleep(3500);
                let apn = textStartsWith('接入点名称 (APN)').findOnce();
                if (apn != null) {
                    let apn_rect = apn.bounds();
                    click(apn_rect.centerX(), apn_rect.centerY());
                    sleep(3500);
                    let settings = className('android.widget.RelativeLayout').find();
                    if (settings.length > 1) {
                        let setting_rect = settings[0].bounds();
                        click(setting_rect.centerX(), setting_rect.centerY());
                        sleep(5500);
                        let back_rect = settings[1].bounds();
                        click(back_rect.centerX(), back_rect.centerY());
                        sleep(3800);
                    } else {
                        throw new Error('APN 接入点设置错误');
                    }
                } else {
                    throw new Error('APN 接入点设置错误');
                }
            } else {
                throw new Error('APN 接入点设置错误');
            }
        } else {
            throw new Error('APN 接入点设置错误');
        }
    } else if (device.device == 'HWSLA-Q') {
        let openRet = app.launchApp('设置');
        if (!openRet) throw new Error('打开设置失败');
        sleep(3500);
        let flyMod = textEndsWith('飞行模式').findOne();
        if (flyMod != null) {
            let flySwitch = className('android.widget.Switch').visibleToUser(true).clickable(true).findOnce();
            if (flySwitch != null) {
                flySwitch.click();
                sleep(12000);
                flySwitch.click();
                sleep(5500);
            } else {
                throw new Error('APN 接入点设置错误');
            }
        } else {
            throw new Error('APN 接入点设置错误');
        }
    } else {
        throw new Error('未适配机型');
    }
}

/**
 * 随机滑动屏幕
 */
function randomMove() {
    let seed = random(1, 100);
    let start_x = device.width / 2;
    let start_y = device.height / 2;
    let end_x = device.width / 2;
    let end_y = 10;
    if (seed < 25) { //东
        start_x = device.width / 2;
        start_y = device.height / 2;
        end_x = device.width - 10;
        end_y = device.height / 2;
    } else if (seed >= 25 && seed < 50) { //西
        start_x = device.width / 2;
        start_y = device.height / 2;
        end_x = 10;
        end_y = device.height / 2;
    } else if (seed >= 50 && seed < 75) { //南
        start_x = device.width / 2;
        start_y = device.height / 2;
        end_x = device.width / 2;
        end_y = device.height - 10;
    }
    let num = randomNum(3, 12);
    for (let i = 0; i < num; i ++) {
        gesture(300, [start_x, start_y], [end_x, end_y]);
        sleep(1500);
    }
    sleep(2000);
}

/**
 * 修改虚拟定位
 */
function moveLocation(appName) {
    if (device.device != 'le_x620') {
        killAllProgress();
    }
    outputMessage('修改虚拟定位');
    let openRet = app.launchApp('多开分身');
    if (!openRet) throw new Error('打开分身工具失败');
    sleep(5500);
    let allow = textEndsWith('允许').findOnce();
    if (allow != null) {
        let allow_rect = allow.bounds();
        click(allow_rect.centerX(), allow_rect.centerY());
        sleep(3500);
    }
    if (device.device == 'le_x620') {
        click(1016, 124);
        sleep(2500);
    } else if (device.device == 'mido' || device.device == 'libra') {
        click(1001, 151);
        sleep(2500);
    } else if (device.device == 'HWSLA-Q') {
        click(676, 95);
        sleep(2500);
    } else {
        throw new Error('未适配的机型');
    }

    let input = className('android.widget.EditText').findOnce();
    if (input != null) {
        setText(appName);
        sleep(2500);
        let confirm = className('android.widget.TextView').text('搜索').findOnce();
        if (confirm != null) {
            let confirm_rect = confirm.bounds();
            click(confirm_rect.centerX(), confirm_rect.centerY());
            sleep(2500);
            setText('');
            sleep(4500);
        }
        sleep(3500);
    }

    let ret = textEndsWith(appName).findOnce();
    if (ret != null) {
        let parent_box = ret.parent().parent().parent().parent().parent();
        let control = parent_box.child(1);
        let control_rect = control.bounds();
        click(control_rect.centerX(), control_rect.centerY());
        sleep(3500);

        let name = textStartsWith(appName).findOnce();
        if (name != null) {
            let gps = textStartsWith('虚拟定位').findOnce();
            if (gps != null) {
                let gps_box = gps.parent().parent();
                let upd = gps_box.child(1);
                let upd_rect = upd.bounds();
                click(upd_rect.centerX(), upd_rect.centerY());
                sleep(4500);
                let confirm = textStartsWith('定位到此').findOnce();
                if (confirm != null) {
                    if (currentCity == null) {
                        let ciryBox = ['郑州', '哈尔滨', '长沙', '南通', '长治', '成都', '乐山', '十堰', '咸宁', '枣庄', '洛阳'];
                        currentCity = ciryBox[Math.floor(Math.random() * ciryBox.length)];
                    }
                    let searchBtn = textEndsWith('搜索地点').findOne(5000);
                    if (searchBtn != null) {
                        let searchRect = searchBtn.bounds();
                        coordinateClick(searchRect.centerX(), searchRect.centerY(), 3000);
                        setText(currentCity);
                        let confirmBtn = textEndsWith('搜索').findOne(5000);
                        if (confirmBtn != null) {
                            confirmBtn.click();
                            sleep(1500);
                            let results = idEndsWith(':id/like').find();
                            if (results.length > 4) {
                                let aim = results[5].bounds();
                                coordinateClick(aim.centerX(), aim.centerY(), 2500);
                                let locationBtn = textStartsWith('定位到此').findOnce();
                                if (locationBtn != null) {
                                    randomMove();
                                    let locationRect = locationBtn.bounds();
                                    click(locationRect.centerX(), locationRect.centerY());
                                    sleep(2500);
                                }
                            }
                        }
                    }
                }
            }
        }
    } else {
        back();
        sleep(2500);
        createSpare(appName);
    }
}

/**
 * 翻页
 */
function swipeThePage() {
    outputMessage('翻页');
    let start_x = device.width / 2;
    let start_y = device.height * 0.6;
    let end_x = device.width / 2;
    let end_y = device.height * 0.3;

    gesture(300, [start_x, start_y], [end_x, end_y]);
    sleep(2000);
}

/**
 * 检测网络是否通畅
 */
function checkInternet() {
    while (true) {
        try {
            let url = HEARTBEAT_URL + deviceInfo();
            //发起网络请求
            let resp = http.get(url);
            if (resp.statusCode == 200) {
                break;
            } else {
                outputMessage('网络不通');
            }
        } catch (e) {
            outputMessage('网络不通，连接异常');
        }
        sleep(4500);
    }
}

/**
 * 卸载app
 * @param {*} packageName 
 */
function unInstallApp(packageName) {
    outputMessage('卸载旧版本app');
    if (device.device == 'le_x620') {
        app.uninstall(packageName);
        sleep(2500);
        let button = className('android.widget.Button').text('确定').findOnce();
        if (button != null) {
            button.click();
        }
    } else if (device.device == 'HWSLA-Q') {
        app.uninstall(packageName);
        sleep(2500);
        let button = className('android.widget.Button').text('卸载').findOnce();
        if (button != null) {
            button.click();
        }
    } else if (device.device == 'mido' || device.device == 'libra') {
        app.uninstall(packageName);
        sleep(2500);
        let button = className('android.widget.Button').text('确定').findOnce();
        if (button != null) {
            button.click();
        }
    } else {
        outputMessage('未适配的手机型号');
    }
}

/**
 * 杀死app
 * @param {*} appName 
 */
function killApp(appName) {
    home();
    sleep(1500);
    if (device.device == 'le_x620') {
        notifications();
        sleep(1500);
        let runningApp = text(appName).findOnce();
        if (runningApp != null) {
            let running_rect = runningApp.bounds();
            click(running_rect.centerX(), running_rect.centerY());
            sleep(2500);
            let is_sure = textMatches(/(.*强.*|.*停.*|.*结.*|.*行.*)/).findOnce();
            if (is_sure != null && is_sure.enabled()) {
                let close = textMatches(/(.*强.*|.*停.*|.*结.*|.*行.*)/).findOnce();
                if (close != null) {
                    let rect = close.bounds();
                    click(rect.centerX(), rect.centerY());
                    sleep(1500);
                }
                close = textMatches(/(.*确.*|.*定.*)/).findOnce();
                if (close != null) {
                    let rect = close.bounds();
                    click(rect.centerX(), rect.centerY());
                    sleep(1500);
                }
                sleep(1000);
                back();
            } else {
                back();
            }
        }
    } else {
        launchApp(appName);
        sleep(10000);
        let packageName = currentPackage();
        app.openAppSetting(packageName);
        text(app.getAppName(packageName)).waitFor();
        sleep(2500);
        let close = textMatches(/(.*强.*|.*停.*|.*结.*|.*行.*)/).findOnce();
        if (close != null) {
            let rect = close.bounds();
            click(rect.centerX(), rect.centerY());
            sleep(3500);

            let sure = textMatches(/(.*确.*|.*定.*)/).findOnce();
            if (sure != null) {
                let rect = sure.bounds();
                click(rect.centerX(), rect.centerY());
                sleep(1500);
            }
            sleep(1000);
            back();
        } else {
            back();
        }
    }

    home();
}

/**
 * 更换设备信息
 * @param {*} appName 
 */
function updateDeviceInfo(appName) {
    home();
    sleep(3000);
    let openRet = app.launchApp('多开分身');
    if (!openRet) throw new Error('打开分身工具失败');
    sleep(5500);
    let allow = textEndsWith('允许').findOnce();
    if (allow != null) {
        let allow_rect = allow.bounds();
        click(allow_rect.centerX(), allow_rect.centerY());
        sleep(3500);
    }
    if (device.device == 'le_x620') {
        click(1016, 124);
        sleep(2500);
    } else if (device.device == 'mido' || device.device == 'libra') {
        click(1001, 151);
        sleep(2500);
    } else if (device.device == 'HWSLA-Q') {
        click(676, 95);
        sleep(2500);
    } else {
        throw new Error('未适配的机型');
    }

    let input = className('android.widget.EditText').findOnce();
    if (input != null) {
        setText(appName);
        sleep(2500);
        let confirm = className('android.widget.TextView').text('搜索').findOnce();
        if (confirm != null) {
            let confirm_rect = confirm.bounds();
            click(confirm_rect.centerX(), confirm_rect.centerY());
            sleep(2500);
            setText('');
            sleep(1500);
        }
    }

    let ret = textEndsWith(appName).findOnce();
    if (ret != null) {
        let parent_box = ret.parent().parent().parent().parent().parent();
        let control = parent_box.child(1);
        let control_rect = control.bounds();
        click(control_rect.centerX(), control_rect.centerY());
        sleep(3500);
        let name = textStartsWith(appName).findOnce();

        if (name != null) {
            let deleteText = textEndsWith('删除分身').findOnce();
            if (deleteText != null) {
                let deleteRect = deleteText.bounds();
                coordinateClick(deleteRect.centerX(), deleteRect.centerY(), 2500);
                let deleteConfirm = textEndsWith('卸载').findOnce();
                if (device.device == 'le_x620') {
                    deleteConfirm = textEndsWith('确定').findOnce();
                }
                if (deleteConfirm != null) {
                    let deleteRect = deleteConfirm.bounds();
                    coordinateClick(deleteRect.centerX(), deleteRect.centerY(), 5500);
                    back();
                    sleep(2500);
                    createSpare(appName);
                } else {
                    throw new Error('找不到确认按钮');
                }
            } else {
                throw new Error('找不到删除按钮');
            }
        }
    } else {
        back();
        sleep(2500);
        createSpare(appName);
    }
}

/**
 * 创建分身
 */
function createSpare(appName) {
    //获取APP本体名字
    let originName = appName.substring(0, appName.indexOf('分身'));
    let titleText = textEndsWith('多开分身').findOnce();
    if (titleText != null) {
        let xPoint = 353;
        let yPoint = 1128;
        if (device.device == 'le_x620') {
            xPoint = 529;
            yPoint = 1828;
        } else if (device.device == 'mido') {
            xPoint = 353;
            yPoint = 1128;
        }
        coordinateClick(xPoint, yPoint, 3500);
        titleText = textEndsWith('选择应用').findOnce();
        if (titleText != null) {
            let appObj = null;
            for (let i = 0; i < 15; i ++) {
                appObj = textEndsWith(originName).findOnce();
                //找到了APP退出循环
                if (appObj != null) {
                    break;
                }
                //没找到APP 翻页继续
                gesture(300, [device.width / 2, device.height / 2], [device.width / 2, 0]);
                sleep(2000);
                gesture(300, [device.width / 2, device.height / 2], [device.width / 2, 0]);
                sleep(2000);
            }
            if (appObj != null) {
                let objBox = appObj.parent().parent();
                let actButton = objBox.child(1);
                let actRect = actButton.bounds();
                coordinateClick(actRect.centerX(), actRect.centerY(), 3500);
                let inputObj = className('android.widget.EditText').findOnce();
                if (inputObj == null) throw new Error('找不到名称输入框');
                //输入分身名称
                setText(appName);
                sleep(2500);
                
                //设置机型
                let mask = textStartsWith('机型伪装').findOnce();
                if (mask != null) {
                    let mask_box = mask.parent().parent();
                    let upd = mask_box.child(1);
                    let upd_rect = upd.bounds();
                    click(upd_rect.centerX(), upd_rect.centerY());
                    sleep(2500);
                    let brand = textStartsWith('手机品牌').findOnce();
                    if (brand != null) {
                        let brand_rect = brand.bounds();
                        click(brand_rect.centerX() + 200, brand_rect.centerY());
                        sleep(2500);
                        swipe(device.width / 2, 300, device.width / 2, device.height / 2, 800);
                        sleep(4000);
                        // let arr = ['华为', '小米', 'OPPO', 'VIVO', '魅族', '索尼', '三星', '锤子', '乐视'];
                        let arr = ['华为', '小米', 'OPPO', 'VIVO'];
                        let phoneName = arr[Math.floor(Math.random() * arr.length)];
                        let types = ['Mate 20 保时捷设计', 'Mate 20 Pro', 'Mate 20 X', 'Mate 20', '荣耀10', '荣耀Magic2', '荣耀 note10', 'P20 Pro', 'P20', 'Mate RS 保时捷版', 'Nova 4', 'Nova 3', 'Nova 2S', '荣耀V20', '荣耀 V10', '荣耀Play'];
                        if (phoneName == '小米') {
                            types = ['小米MIX3', '小米8 SE', '小米8', '小米6X', '黑鲨', '小米6', '小米MIX2', '小米MIX', '小米5', '小米5X', '红米4X', '红米Note 4X', '小米Note 2', '小米5s', '小米5s Plus', '红米4'];
                        } else if (phoneName == 'OPPO') {
                            types = ['R17 Pro', 'R17', 'K1', 'Find X', 'A7x', 'R15', 'A5', 'A3', 'A1', 'R11 plus', 'R11', 'R11s', 'R9s', 'R9m', 'R9 plus', 'R8', 'R7'];
                        } else if (phoneName == 'VIVO') {
                            types = ['NEX 2', 'NEX S', 'NEX', 'X23', 'X21', 'Z3', 'Z1', 'Y97', 'Y85', 'Y83', 'X20 Plus', 'X20A', 'X20', 'Xplay6', 'X9', 'X9s', 'X9 Plus'];
                        } else if (phoneName == '魅族') {
                            types = ['16th Plus', '16th', '16x', 'E3', 'M15', 'PRO7 Plus', 'PRO7', 'PRO6 Plus', 'PRO6', 'm6 note', 'm5', 'm5 note', 'MX6', 'MX5', 'm3'];
                        } else if (phoneName == '索尼') {
                            types = ['Xperia XZ Premium', 'Xperia XZs', 'Xperia XZ1', 'Xperia XZ2'];
                        } else if (phoneName == '三星') {
                            types = ['Galaxy Note9', 'Galaxy S9+', 'Galaxy S9', 'Galaxy S8+', 'Galaxy S8', 'Galaxy S7', 'GALAXY S6', 'GALAXY S5', 'W2019', 'W2018'];
                        } else if (phoneName == '锤子') {
                            types = ['R1', 'T3', 'T2', 'T1', '坚果Pro'];
                        } else if (phoneName == '乐视') {
                            types = ['乐Max', '乐1S Pro X800', '乐1 X608', '乐1 X600', '乐1S X500'];
                        }
                        let typeName = types[Math.floor(Math.random() * types.length)];
                        let mobile = textStartsWith(phoneName).findOnce();
                        if (mobile != null) {
                            let mobile_rect = mobile.bounds();
                            click(mobile_rect.centerX(), mobile_rect.centerY());
                            sleep(2500);
                            let device = textStartsWith('手机型号').findOnce();
                            if (device != null) {
                                let device_rect = device.bounds();
                                click(device_rect.centerX() + 200, device_rect.centerY());
                                sleep(2500);
                                let type = textStartsWith(typeName).findOnce();
                                log(typeName);
                                if (type != null) {
                                    let type_rect = type.bounds();
                                    coordinateClick(type_rect.centerX(), type_rect.centerY(), 2500);
                                } else {
                                    throw new Error('找不到手机型号');
                                }
                                let change = textStartsWith('换一换').findOnce();
                                if (change != null) {
                                    let change_rect = change.bounds();
                                    click(change_rect.centerX(), change_rect.centerY());
                                    sleep(1200);
                                    click(change_rect.centerX(), change_rect.centerY());
                                    sleep(1200);
                                    click(change_rect.centerX(), change_rect.centerY());
                                    sleep(1200);
                                    click(change_rect.centerX(), change_rect.centerY());
                                    sleep(1200);
                                    click(change_rect.centerX(), change_rect.centerY());
                                    sleep(1200);
                                    //保存更新后的设备信息
                                    // recordDeviceInfo(phoneName, typeName);
    
                                    let did = textStartsWith('启用机型伪装').findOnce();
                                    if (did != null) {
                                        let did_rect = did.bounds();
                                        click(did_rect.centerX(), did_rect.centerY());
                                        sleep(2500);
                                    }
                                }
                            }
                        } else {
                            throw new Error('找不到手机品牌');
                        }
                    }
                } else {
                    throw new Error('找不到机型伪装按钮');
                }
                //设置定位
                let gps = textStartsWith('虚拟定位').findOnce();
                if (gps != null) {
                    let gps_box = gps.parent().parent();
                    let upd = gps_box.child(1);
                    let upd_rect = upd.bounds();
                    coordinateClick(upd_rect.centerX(), upd_rect.centerY(), 4500);
                    if (currentCity == null) {
                        let ciryBox = ['郑州', '哈尔滨', '长沙', '南通', '长治', '成都', '乐山', '十堰', '咸宁', '枣庄', '洛阳'];
                        currentCity = ciryBox[Math.floor(Math.random() * ciryBox.length)];
                    }
                    let searchBtn = textEndsWith('搜索地点').findOne(5500);
                    if (searchBtn != null) {
                        let searchRect = searchBtn.bounds();
                        coordinateClick(searchRect.centerX(), searchRect.centerY(), 3000);
                        setText(currentCity);
                        sleep(2500);
                        let confirmBtn = textEndsWith('搜索').findOne(5000);
                        if (confirmBtn != null) {
                            confirmBtn.click();
                            sleep(3500);
                            let results = idEndsWith(':id/like').find();
                            if (results.length > 4) {
                                let aim = results[5].bounds();
                                coordinateClick(aim.centerX(), aim.centerY(), 2500);
                                let confirm = textStartsWith('定位到此').findOnce();
                                if (confirm != null) {
                                    randomMove();
                                    let confirm_rect = confirm.bounds();
                                    click(confirm_rect.centerX(), confirm_rect.centerY());
                                    sleep(2500);
                                }
                            } else {
                                back();
                                sleep(1500);
                                back();
                                sleep(1500);
                            }
                        } else {
                            throw new Error('找不到搜索按钮');
                        }
                    } else {
                        throw new Error('找不到搜索地点');
                    }
                } else {
                    throw new Error('找不到虚拟定位按钮');  
                }
                
                //确定制作
                let makeBtn = textEndsWith('开始制作').findOnce();
                if (makeBtn != null) {
                    let makeRect = makeBtn.bounds();
                    coordinateClick(makeRect.centerX(), makeRect.centerY(), 15000);
                    //安装APP
                    installApk();
                }
            } else {
                throw new Error('找不到应用' + originName);
            }
        } else {
            throw new Error('选择应用场景错误');
        }
    } else {
        throw new Error('分身列表场景错误');
    }
}

function randomNum(minNum, maxNum) {
    switch (arguments.length) {
        case 1:
            return parseInt(Math.random() * minNum + 1, 10);
            break;
        case 2:
            return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
            break;
        default:
            return 10;
            break;
    }
}

/**
 * 连接VPN
 */
function connectVpn() {
    killAllProgress();

    app.launchApp('万变代理');
    sleep(5500);

    let buttonLogin = className('android.widget.Button').text('登录').clickable(true).findOnce();
    if (buttonLogin != null) {
        id('ih').setText('18635197772');
        sleep(800);
        id('ik').setText('shileilei');
        sleep(800);
        let buttonRemember = className('android.widget.CheckBox').text('记住密码').checked(false).findOnce();
        if (buttonRemember != null) {
            buttonRemember.click();
            sleep(1500);
        }

        buttonLogin.click();
        sleep(3500);
    }

    let connectErr = textEndsWith('连接失败').findOnce();
    if (connectErr != null) {
        let buttonConfirm = textEndsWith('确定').clickable(true).findOnce();
        if (buttonConfirm != null) {
            buttonConfirm.click();
            sleep(2500);
        }
    }

    let buttonCancelCon = className('android.widget.Button').text('取消连接').clickable(true).findOnce();
    if (buttonCancelCon != null) {
        buttonCancelCon.click();
        sleep(2500);
    }

    back();
    sleep(2500);

    let buttonClose = textStartsWith('一键断开').clickable(true).findOnce();
    if (buttonClose != null) { //连上了VPN
        buttonClose.click();
        let timer = 660;
        while (timer > 0) {
            timer -= 1;
            sleep(1000);
            if (timer % 5 == 0) {
                outputMessage('等待: ' + timer + ' 秒');
            }
        }
    }

    let buttonBx = idEndsWith(':id/bx').clickable(true).findOnce();
    if (buttonBx != null) {
        buttonBx.click();
        sleep(4500);
        let buttonXl = textStartsWith('混拨线路').findOnce();
        if (buttonXl != null) {
            let rectXl = buttonXl.bounds();
            click(rectXl.centerX(), rectXl.centerY());
            sleep(6500);
            let buttonType = idEndsWith(':id/fo').findOnce();
            if (buttonType != null) {
                let rectType = buttonType.bounds();
                click(rectType.centerX(), rectType.centerY());
                sleep(3500);
                let buttonCountry = textStartsWith('国内动态共享').findOnce();
                if (buttonCountry != null) {
                    let rectCountry = buttonCountry.bounds();
                    click(rectCountry.centerX(), rectCountry.centerY());
                    sleep(3500);

                    let buttonSearch = textStartsWith('按条件搜索').findOnce();
                    if (buttonSearch != null) {
                        let rectSearch = buttonSearch.bounds();
                        click(rectSearch.centerX(), rectSearch.centerY());
                        sleep(4500);
                        buttonJds = idEndsWith(':id/ey').find();
                        if (buttonJds.length > 0) {
                            let buttonJd = buttonJds[Math.floor(Math.random() * buttonJds.length)];
                            let rectJd = buttonJd.bounds();
                            click(rectJd.centerX(), rectJd.centerY());
                            sleep(3500);
                            let buttonSure = className('android.widget.Button').clickable(true).text('确定').findOnce();
                            if (buttonSure != null) {
                                buttonSure.click();
                                sleep(2500);
                            }
                            checkLink();
                        } else {
                            back();
                            sleep(1500);
                        }
                    }
                }
            } else {
                back();
                sleep(1500);
            }
        } else {
            back();
            sleep(1500);
        }
    }
}

/**
 * 检查连接状态
 */
function checkLink() {
    let i = 0;
    while (true) {
        if (i >= 30) { //超时判定
            let buttonCancel = textEndsWith('取消连接').clickable(true).findOnce();
            if (buttonCancel != null) {
                buttonCancel.click();
                sleep(3500);
            }
            throw new Error('连接失败');
        }
        i++;
        let buttonClose = textStartsWith('一键断开').findOnce();
        if (buttonClose != null) { //连上了VPN
            break;
        }
        sleep(800);
    }
}

function ipReport() {
    let url = "http://db.leyouapp.cn:8880/app/ip" + deviceInfo();
    let res = http.get(url);
    outputMessage('statusCode: ' + res.statusCode);
    if (res.statusCode == 200) {
        let resp = JSON.parse(res.body.string());
        outputMessage(resp);
    }
}

/**
 * 连接天天动态IP VPN
 */
function connectDongtaiIp() {
    killAllProgress();

    app.launchApp('天天动态IP');
    for (let i = 0; i < 5; i++) {
        sleep(800);
        let widget = textMatches(/(.*允许.*)/).clickable(true).findOnce();
        if (widget != null) {
            widget.click();
            sleep(3500);
        }
    }

    sleep(5500);

    let buttonLogin = idEndsWith('btnlogin').clickable(true).findOnce();
    if (buttonLogin != null) {
        buttonLogin.click();
        sleep(4500);
        let buttonForce = className('android.widget.Button').text('强制登录').clickable(true).findOnce();
        if (buttonForce != null) {
            buttonForce.click();
            sleep(4500);
        }
    }

    let buttonMain = idEndsWith(':id/bnv_item1').clickable(true).findOnce();
    if (buttonMain != null) {
        buttonMain.click();
        sleep(3500);
    }
    let oldIp = null;
    let textCurrent = idEndsWith(':id/currentchooseline').findOnce();
    if (textCurrent != null && textCurrent.text() != "未选择线路") {
        let textConnect = textMatches(/(.*已连接.*)/).findOnce();
        if (textConnect != null) {
            let ipContent = textStartsWith('线路IP:').findOne(6000);
            if (ipContent != null) {
                oldIp = ipContent.text();
                outputMessage('当前线路: ' + oldIp);
                let buttonConnect = idEndsWith('maincpv').clickable(true).findOnce();
                if (buttonConnect != null) {
                    buttonConnect.click();
                    let timer = 25;
                    while (timer > 0) {
                        timer -= 1;
                        sleep(1000);
                        if (timer % 5 == 0) {
                            outputMessage('等待: ' + timer + ' 秒');
                        }
                    }
                } else {
                    throw new Error('找不到断开按钮');
                }
            } else {
                let cutBtn = idEndsWith('maincpv').clickable(true).findOnce();
                if (cutBtn != null) {
                    cutBtn.click();
                    sleep(3500);
                }
                throw new Error('找不到线路IP');
            }
        }

        let buttonConnect = idEndsWith('maincpv').clickable(true).findOnce();
        if (buttonConnect != null) {
            buttonConnect.click();
            sleep(2500);
            let buttonConfirm = textStartsWith('确定').clickable(true).findOnce();
            if (buttonConfirm != null) {
                buttonConfirm.click();
                sleep(4500);
            }
            checkDongtaiIpLink(oldIp);
            ipReport();
        } else {
            throw new Error('找不到连接按钮');
        }
    } else {
        let buttoonChoose = idEndsWith('mainchooselinelayout').clickable(true).findOnce();
        if (buttoonChoose != null) {
            buttoonChoose.click();
            sleep(3500);
            let arrLine = ['全国超级混拨-01', '全国超级混拨-02', '全国超级混拨-03', '全国超级混拨-04'];
            let textLine = arrLine[Math.floor(Math.random() * arrLine.length)];
            let buttonLine = textStartsWith(textLine).findOnce();
            if (buttonLine != null) {
                let rectLine = buttonLine.bounds();
                click(rectLine.centerX(), rectLine.centerY());
                sleep(3500);
                let buttonConnect = idEndsWith('maincpv').clickable(true).findOnce();
                if (buttonConnect != null) {
                    buttonConnect.click();
                    sleep(2500);
                    let buttonConfirm = textStartsWith('确定').clickable(true).findOnce();
                    if (buttonConfirm != null) {
                        buttonConfirm.click();
                        sleep(4500);
                    }
                    checkDongtaiIpLink();
                    ipReport();
                } else {
                    throw new Error('连接失败2');
                }
            } else {
                throw new Error('连接失败3');
            }
        } else {
            throw new Error('连接失败4');
        }
    }
}

/**
 * 切断天天动态IP VPN
 */
function cutdownDongtaiIp() {
    killAllProgress();

    app.launchApp('天天动态IP');
    for (let i = 0; i < 5; i++) {
        sleep(800);
        let widget = textMatches(/(.*允许.*)/).clickable(true).findOnce();
        if (widget != null) {
            widget.click();
            sleep(3500);
        }
    }

    sleep(5500);

    let buttonLogin = idEndsWith('btnlogin').clickable(true).findOnce();
    if (buttonLogin != null) {
        buttonLogin.click();
        sleep(4500);
        let buttonForce = className('android.widget.Button').text('强制登录').clickable(true).findOnce();
        if (buttonForce != null) {
            buttonForce.click();
            sleep(4500);
        }
    }

    let buttonMain = idEndsWith(':id/bnv_item1').clickable(true).findOnce();
    if (buttonMain != null) {
        buttonMain.click();
        sleep(3500);
    }

    let textCurrent = idEndsWith(':id/currentchooseline').findOnce();
    if (textCurrent != null && textCurrent.text() != "未选择线路") {
        let textConnect = textMatches(/(.*已连接.*)/).findOnce();
        if (textConnect != null) {
            let cutBtn = idEndsWith('maincpv').clickable(true).findOnce();
            if (cutBtn != null) {
                cutBtn.click();
                sleep(3500);
            }
        }
    }
}

/**
 * 检查连接状态
 */
function checkDongtaiIpLink(oldIp) {
    let i = 0;
    while (true) {
        if (i >= 30) { //超时判定
            throw new Error('连接失败');
        }
        i++;
        let textConnect = textMatches(/(.*已连接.*)/).findOnce();
        if (textConnect != null) { //连上了VPN
            // let ipContent = textStartsWith('线路IP:').findOne(30000);
            // if (ipContent != null) {
            //     let currentIp = ipContent.text();
            //     if (currentIp.length > 5) {
            //         vpnIp = currentIp.substring(6, currentIp.length);
            //     }
            // }
            // if (oldIp != null && ipContent != null) {
                // let newIp = ipContent.text();
                // outputMessage('原IP: ' + oldIp);
                // outputMessage('新IP: ' + newIp);
                // if (newIp == oldIp) {
                //     throw new Error('线路IP未改变');
                // } else {
                //同步最新的链接城市
                getCurrentLineCity();
                break;
                // }
            // } else {
            //     getCurrentLineCity();
            //     break;
            // }
        }
        sleep(800);
    }
}

/**
 * 倒计时工具
 * @param {*} timer 
 */
function timingWheel(timer) {
    while (timer > 0) {
        timer -= 1;
        sleep(1000);
        if (timer % 5 == 0) {
            outputMessage('等待: ' + timer + ' 秒');
        }
    }
}

/**
 * 获取当前线路连接的城市
 */
function getCurrentLineCity() {
    let currentLine = idEndsWith(':id/currentchooseline').findOne(4000);
    if (currentLine != null) {
        let lineText = currentLine.text();
        let reg = /\>.{0,}/;
        let ret = reg.exec(lineText);
        if (ret.length > 0) {
            let mixCityLong = ret[0];
            let end = -1;
            end = mixCityLong.indexOf('电信');
            if (end == -1) {
                end = mixCityLong.indexOf('联通');
                if (end == -1) {
                    end = mixCityLong.indexOf('移动');
                }
            }
            if (end != -1) {
                currentCity = mixCityLong.substring(2, end);
                outputMessage('当前城市: ' + currentCity);
            }
        }
    } else {
        throw new Error('获取当前城市信息失败');
    }
}

/**
 * 获取范围随机整数
 * @param {*} min 
 * @param {*} max 
 */
function getRandom(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

function closeInstall() {
    while (true) {
        let buttonClose = idEndsWith(':id/cancel_btn').findOnce();
        if (device.device == 'HWSLA-Q' || device.device == 'le_x620') {
            buttonClose = idEndsWith(':id/cancel_button').findOnce();
        }
        if (buttonClose != null) {
            let ret = textStartsWith(AppName).findOnce();
            if (ret == null) {
                let seed = getRandom(1, 100);
                //20%的概率安装应用
                if (seed < 20) {
                    installApk();
                } else { //80%的概率取消安装
                    let rectClose = buttonClose.bounds();
                    coordinateClick(rectClose.centerX(), rectClose.centerY(), 2500);
                }
            }
        }
        sleep(2000);
    }
}

/** 
 * 判断VPN是否有效
 * @author guxiang
 */
function checkVpnIp() {
    let url = "http://db.leyouapp.cn:8880/contrastIp?ip=" + vpnIp;
    let res = http.get(url);
    if (res.statusCode == 200) {
        let resp = JSON.parse(res.body.string());
        outputMessage('VPN的IP是: ' + vpnIp);
        outputMessage('status: ' + resp.status);
        outputMessage('msg: ' + resp.msg);
        if (resp.status) {
            return true;
        }
    }
    return false;
}

/**
 * 记录设备信息
 */
function recordDeviceInfo(phoneName, typeName) {
    let imeiObj = textStartsWith('8689').findOnce();
    if (imeiObj != null) {
        let imeiCode = imeiObj.text();
        let url = "http://clone.leyouhome.cn/phone/record?phoneName=" + phoneName + "&typeName=" + typeName + "&imeiCode=" + imeiCode;
        http.get(url);
    }
}